import {Component, OnInit} from '@angular/core';
import {Store} from '@ngrx/store';
import {Logout} from '../../actions/auth.actions';
import {AlertController, Events, ModalController, NavController, ToastController} from '@ionic/angular';
import {AuthState} from '../../reducers/auth.reducer';
import {BasePage} from '../../common/basePage';
import {HttpService} from '../../services/http.service';
import {UtilService} from '../../services/util.service';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {Storage} from '@ionic/storage';
import {AppConfig} from '../../common/app-config.enum';
import {ConfigService} from '../../services/config.service';
import {IframePageComponent} from '../../components/iframe-page/iframe-page.component';

/**
 * 安全中心
 */
@Component({
  selector: 'app-safety-center',
  templateUrl: './safety-center.page.html',
  styleUrls: ['./safety-center.page.scss'],
})
export class SafetyCenterPage extends BasePage implements OnInit {

  public userInfo: any = {};

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              public configService: ConfigService,
              private modalCtrl: ModalController,
              private alertCtrl: AlertController,
              private service$: HttpService,
              private utilService: UtilService,
              private storage: Storage,
              private events: Events,
              private store: Store<AuthState>) {
    super(navCtrl, toastCtrl);
    events.subscribe(AppConfig.TOPIC_UNDO_LIST, () => {
      this.getData();
    });
  }

  ngOnInit() {
    this.getData();
  }

  private async getData() {
    const obj = await this.service$.doRequest(UrlAndOPT.auth_safety_center).toPromise();
    // 判断是否设置了手势解锁
    const lock = await this.storage.get(AppConfig.GESTURE_LOCK);
    if (obj) {
      this.userInfo = obj;
    }
    this.userInfo['isGestureLock'] = !!lock;

  }

  // 前往存管信息(解除)页(如果未开通资金存管，由于路由守卫的作用，会自动跳转至开通页面)
  pushAccount() {
    this.navCtrl.navigateForward(['/auth/user-account-unbind']);
  }

  // 借款签约
  pushSignLoan() {
    let OPT = null;
    switch (this.userInfo['makeSignLoan']) {
      case 1: // 签约
        OPT = UrlAndOPT.make_sign_loan;
        break;
      case -1: // 解约
        OPT = UrlAndOPT.un_make_sign_loan;
        break;
      case 0:
        this.showToast('当前状态无法操作，请稍后再试');
        break;
      default:
        break;
    }
    if (OPT) {
      this.service$.doRequest(OPT)
        .subscribe(async (obj) => {
          if (obj) {
            if (obj['url']) {
              // 打开资金存管开户页面model
              const modal = await this.modalCtrl.create({
                component: IframePageComponent,
                componentProps: {
                  title: '借款签约',
                  url: obj['url']
                }
              });
              await modal.present();
              // 关闭model后，确认签约状态
              await modal.onDidDismiss();
            } else {
              this.showToast('解约成功！');
            }
            // 发出流程变化通知
            this.events.publish(AppConfig.TOPIC_UNDO_LIST);
          }
        });
    }
  }

  // 被担保签约
  pushAdvance() {
    let OPT = null;
    switch (this.userInfo['makeAdvance']) {
      case 1: // 签约
        OPT = UrlAndOPT.make_advance;
        break;
      case -1: // 解约
        OPT = UrlAndOPT.un_make_advance;
        break;
      case 0:
        this.showToast('当前状态无法操作，请稍后再试');
        break;
      default:
        break;
    }
    if (OPT) {
      this.service$.doRequest(OPT)
        .subscribe(async (obj) => {
          if (obj) {
            if (obj['url']) {
              // 打开资金存管开户页面model
              const modal = await this.modalCtrl.create({
                component: IframePageComponent,
                componentProps: {
                  title: '被担保签约',
                  url: obj['url']
                }
              });
              await modal.present();
              // 关闭model后，确认签约状态
              await modal.onDidDismiss();
            } else {
              this.showToast('解约成功！');
            }
            // 发出流程变化通知
            this.events.publish(AppConfig.TOPIC_UNDO_LIST);
          }
        });
    }
  }

  // 前往银行卡页面
  pushCard() {
    this.navCtrl.navigateForward(['/auth/user-card']);
  }

  // 开通电子签章
  openES() {
    if (!this.userInfo['isSignature']) {
      this.service$.doUndo(null, {step: '电子签章'});
    }
  }

  // 修改交易密码
  pushPaymentPwd() {
    if (this.userInfo['resetPaymentPwd']) {
      this.service$.doRequest(UrlAndOPT.auth_payment_pwd)
        .subscribe(async (obj) => {
          if (obj) {
            const modal = await this.modalCtrl.create({
              component: IframePageComponent,
              componentProps: {
                title: '修改交易密码',
                url: obj['url']
              }
            });
            await modal.present();
            await modal.onDidDismiss();
            // 发出流程变化通知
            this.events.publish(AppConfig.TOPIC_UNDO_LIST);
          }
        });
    }
  }

  // 确认退出登录
  async confirmLogout() {
    const alert = await this.alertCtrl.create({
      header: '退出登录',
      message: '您确定要退出当前账号吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        }, {
          text: '确定',
          handler: async () => {
            await this.doLogout();
          }
        }
      ]
    });

    await alert.present();
  }

  // 执行退出登录 userId  deviceType
  private doLogout() {
    this.service$.doRequest(UrlAndOPT.auth_logout)
      .subscribe(async (obj) => {
        if (obj) {
          await this.service$.clearUserInfo();
          this.store.dispatch(new Logout({status: 0, userInfo: {}, response: null}));
          await this.showToast('已退出登录');
          await this.navCtrl.navigateRoot('/tabs/home');
        }
      });
  }

}
